﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class UserPanel : MonoBehaviour 
{
	public Server server;

	// data
	string question = "";
	string answers = ""; // JSON of answers (todo: make it more user-friendly)
	Dictionary<string, bool> dictAnswers = new Dictionary<string, bool>();
	//bool showResults = false;

	int wLeft = 200;
	int wRight = 500;
	int lineHeight = 25;

	public void SetQuestion(string q, string a)
	{
		question = q;
		answers = a;

		dictAnswers = ParseAnswers(a);
	}


	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {
	
	}

	void OnGUI()
	{

		Rect r = new Rect(5, 5, wLeft, lineHeight);

		if (GUI.Button(r, "REFRESH"))
		{
			//showResults = false;
			server.RefreshQuestion();
		}

		r.y += r.height + 5;
		if (GUI.Button(r, "VOTE"))
		{
			server.SendVote(question, GetSelectedVote());
		}

		r.x = 25;
		r.y += r.height + 5;
		GUI.Label(r, "QUESTION:");

		r.x = 5;
		r.y += r.height + 5;
		//r.x += wLeft;
		//r.width = wRight;
		GUI.Label(r, question);

		r = new Rect(25, r.y + r.height + 5, wLeft, lineHeight);
		GUI.Label(r, "ANSWERS:");

		r = new Rect(5, r.y, wRight, lineHeight);

		List<string> keys = new List<string>(dictAnswers.Keys);
		foreach (string key in keys)
		{
			r.y += r.height;
			dictAnswers[key] = GUI.Toggle(r, dictAnswers[key], key);
		}

/*
		for(int i=0; i<dictAnswers.Count; ++i)
		{
			KeyValuePair<string, bool> answer = dictAnswers[i];
			dictAnswers[answer.Key] = GUI.Toggle(r, answer.Value, answer.Key);
		}


		Dictionary<string, double> dictionary = new Dictionary<string, double>();
		var keys = new List<string>(dictionary.Keys);
		foreach (string key in keys)
		{
		   dictionary[key] = Math.Round(dictionary[key], 3);
		}
*/
		/*foreach(KeyValuePair<string, bool> entry in dictAnswers)
		{
			r.y += r.height;
			entry.Value = GUI.Toggle(r, entry.Value, entry.Key);
		}
		*/
/*
		r.x += wLeft;
		r.width = wRight;
		GUI.Label(r, answers);
*/
		//r = new Rect(5, r.y + r.height + 5, wLeft, 40);

		
	/*	r.x += wRight;
		bool showResultsNow = GUI.Toggle(r, showResults, "SHOW RESULTS");
		if (showResults != showResultsNow)
			server.StartResults(showResultsNow);
		showResults = showResultsNow;
	*/
	}

	Dictionary<string, bool> ParseAnswers(string answers)
	{
		Dictionary<string, bool> dict = new Dictionary<string, bool>();
		string[] lines = answers.Split(new string[] { "\r\n", "\n" }, System.StringSplitOptions.RemoveEmptyEntries);

		foreach (string line in lines)
			dict.Add(line, false);

		return dict;
	} 

	string GetSelectedVote()
	{
		foreach (KeyValuePair<string, bool> entry in dictAnswers)
			if (entry.Value)
				return entry.Key;
		return "";
	}
}
